package it.davial.mgwt.server;

import static it.softphone.commons.util.LogUtil.logger; 
import static it.davial.mgwt.server.Utility.ManagmentId;
import static  it.davial.mgwt.server.Sql.Patient.*;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;

import it.davial.mgwt.client.Patient;


public class PatientUtils {

	
	/**
	 * find all patient without criteria
	 * @return List<Patient>
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public static List<Patient> findAllPatient()throws Exception{
		
		EntityManager newEm=null;
		List<Patient> result=new ArrayList<Patient>();
		Utility.Logs.startFunction("PatientUtils", "findAllPatient", new String[]{});
		
		try{
			logger.warn("JpaUtility.getEntityFactory");
			EntityManagerFactory emf=JpaUtility.getEntityFactory();
			if (emf==null){
				logger.warn("EntityManagerFactory is null...");
				throw new Exception();
			}
			logger.warn("emf.createEntityManager");
			newEm =emf.createEntityManager();
			
			result =(List<Patient>)newEm.createNativeQuery(SELECT_ALL,Patient.class).getResultList();
	
			logger.info(" Patient(s) found:".concat(String.valueOf(result.size()))  );

			
		}catch(javax.persistence.NoResultException e){
			logger.warn("PatientUtils:findAllPatient",e);
		}catch(Exception e){
			logger.error("PatientUtils:findAllPatient",e);
			throw e;
		}finally{
			if (newEm!=null)newEm.close();
		}
		return result;
	}
	
	/**
	 * find all patient with criteria
	 * @return Patient
	 * @throws Exception
	 */
	public static Patient findPatientById(int id)throws Exception{
		
		EntityManager newEm=null;
		Patient result=null;
		Utility.Logs.startFunction("PatientUtils", "findPatientById", new String[]{String.valueOf(id)});
		
		try{
			EntityManagerFactory emf=JpaUtility.getEntityFactory();
			if (emf==null){
				logger.warn("EntityManagerFactory is null...");
				throw new Exception();
			}
			newEm =emf.createEntityManager();
			
			
			result =(Patient)newEm.createNativeQuery(SELECT_BY_ID,Patient.class).
										setParameter(1,id ).getSingleResult();
	
			logger.info(" Patient found:".concat(String.valueOf(result))  );
			
		}catch(javax.persistence.NoResultException e){
			logger.warn("PatientUtils:findPatientById",e);
		}catch(Exception e){
			logger.error("PatientUtils:findPatientById",e);
			throw e;
		}finally{
			if (newEm!=null)newEm.close();
		}
		return result;
	}
	
	/**
	 * find all patient with criteria
	 * @return List<Patient>
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public static List<Patient> findPatientBySurnameAndDate(String surname,String date)throws Exception{
		
		EntityManager newEm=null;
		List<Patient> result=null;
		
		surname=Utility.StringUtils.nullUtility(surname);
		date=Utility.StringUtils.nullUtility(date);

		Utility.Logs.startFunction("PatientUtils", "findPatientBySurnameAndDate", new String[]{surname,date});
		
		try{
			EntityManagerFactory emf=JpaUtility.getEntityFactory();
			if (emf==null){
				logger.warn("EntityManagerFactory is null...");
				throw new Exception();
			}
			newEm =emf.createEntityManager();
			
			
			result =(List<Patient>)newEm.createNativeQuery(SELECT_BY_SURNAME_DATE,Patient.class).
										setParameter(1,surname ).
										setParameter(2,surname ).
										setParameter(3,date ).
										setParameter(4,date ).
										getResultList();
	
			logger.info(" Patient(s) found:".concat(String.valueOf(result.size()))  );
			
		}catch(javax.persistence.NoResultException e){
			logger.warn("PatientUtils:findPatientBySurnameAndDate",e);
		}catch(Exception e){
			logger.error("PatientUtils:findPatientBySurnameAndDate",e);
			throw e;
		}finally{
			if (newEm!=null)newEm.close();
		}
		return result;
	}
	
	/**
	 * create a patient
	 * @return boolean
	 * @throws Exception
	 */
	public static boolean createPatient(Patient patient)throws Exception{
		EntityManager newEm=null;
		EntityTransaction tx =null;
		Utility.Logs.startFunction("PatientUtils", "createPatient", new String[]{patient.toString()});
		try{
			EntityManagerFactory emf=JpaUtility.getEntityFactory();
			if (emf==null){
				logger.warn("EntityManagerFactory is null...");
				throw new Exception();
			}
			newEm =emf.createEntityManager();
			tx = newEm.getTransaction();
		    tx.begin();
		    patient.setIdPatient(ManagmentId.getNextId(IdEntity.PATIENT));
		    patient.setDataInsert(Utility.Date.nowDateDb());
		    patient.setDataUpdate(Utility.Date.nowDateDb());
		    patient.setDataBirth(Utility.Date.webFormatToDateDb(patient.getDataBirth()));
			newEm.persist(patient);
			logger.info("patient created..." );
			tx.commit();
		}catch(javax.persistence.NoResultException e){
			logger.warn("PatientUtils:findPatientById",e);
		} catch(Exception e){
			tx.rollback();
			logger.error("PatientUtils:createPatient",e);
			throw e;
		}finally{
			if (newEm!=null)newEm.close();
		}
		return true;    
	}
	
	/**
	 * merge a patient
	 * @return boolean
	 * @throws Exception
	 */
	public static boolean mergePatient(Patient patient)throws Exception{
		EntityManager newEm=null;
		EntityTransaction tx =null;
		Utility.Logs.startFunction("PatientUtils", "merge", new String[]{patient.toString()});
		try{
			EntityManagerFactory emf=JpaUtility.getEntityFactory();
			if (emf==null){
				logger.warn("EntityManagerFactory is null...");
				throw new Exception();
			}
			newEm =emf.createEntityManager();
			tx = newEm.getTransaction();
		    tx.begin();
		    patient.setDataInsert(Utility.Date.webFormatToDateDb(patient.getDataInsert()));
		    patient.setDataUpdate(Utility.Date.nowDateDb());
		    patient.setDataBirth(Utility.Date.webFormatToDateDb(patient.getDataBirth()));
		    logger.info("set date....".concat(patient.toString()));
			newEm.merge(patient);
			logger.info("patient mergeed..." );
			 tx.commit();
		}catch(Exception e){
			tx.rollback();
			logger.error("PatientUtils:mergePatient",e);
			throw e;
		}finally{
			if (newEm!=null)newEm.close();
		}
		return true;
	}
	
	/**
	 * delete a patient
	 * @return boolean
	 * @throws Exception
	 */
	public static boolean deletePatient(Patient patient)throws Exception{
		EntityManager newEm=null;
		EntityTransaction tx =null;
		Utility.Logs.startFunction("PatientUtils", "delete", new String[]{patient.toString()});
		try{
			EntityManagerFactory emf=JpaUtility.getEntityFactory();
			if (emf==null){
				logger.warn("EntityManagerFactory is null...");
				throw new Exception();
			}
			newEm =emf.createEntityManager();
			tx = newEm.getTransaction();
		    tx.begin();
			patient.setState(Utility.Costants.DISABLED);
			logger.info(String.format("patient delete...[%s]",patient) );
			patient.setDataUpdate(Utility.Date.nowDateDb());
		    patient.setDataInsert(Utility.Date.webFormatToDateDb(patient.getDataInsert()));
		    patient.setDataBirth(Utility.Date.webFormatToDateDb(patient.getDataBirth()));
		    Utility.Logs.startFunction("PatientUtils", "delete", new String[]{patient.toString()});
			newEm.merge(patient);
			
			tx.commit();
		}catch(Exception e){
			tx.rollback();
			logger.error("PatientUtils:deletePatient",e);
			throw e;
		}finally{
			if (newEm!=null)newEm.close();
		}
		return true;
	}
	
	
}
